import {useEffect,useState} from "react";
import {flushSync} from "react-dom";
import './Detail.less'
import api from '@/api'

import { Badge} from 'antd-mobile'
import {LeftOutline, LikeOutline, MessageOutline, MoreOutline, StarOutline} from 'antd-mobile-icons'
import SkeletonScreen from "../components/SkeletonScreen";

const Detail = (props) => {
    let { navigate , params} = props
    let [info , setInfo] = useState(null),
        [extra , setExtra] = useState(null)
    let link
    const setStyle = (date) => {
        const {css} = date
        if(!css) return
        link = document.createElement('link')
        link.rel = "stylesheet";
        link.href = css
        document.head.append(link)
    }
    const setImage = (date)=> {
        const imgBox = document.querySelector('.img-place-holder')
        if(!imgBox) return
        const img = new Image()
        img.src = date?.images[0]
        img.onload = () => {
            imgBox.appendChild(img)
        }
        img.onerror = () => {
            const topBox = document.querySelector('.headline')
            topBox.parentNode.removeChild(topBox)
        }
    }


    // 获取新闻详情
    useEffect(() => {
        (async () => {
            try {
                let date = await api.queryNewsInfo(params.id)
                flushSync(() =>{
                    setInfo(date)
                    setStyle(date)
                })
                setImage(date)

            }catch (_){}
        })()
        return () => {
            if(link) document.head.removeChild(link)
        }
    },[])

    // 获取新闻点赞数量
    useEffect(() => {
        (async () => {
            try {
                let date = await api.queryStoryExtra(params.id)
                setExtra(date)
            }catch (_){}
        })()

    },[])

    return <div className={'detail-box'}>
                {/*新闻内容*/}
                {
                    !info ? <SkeletonScreen/> :
                    <div className={'content'} dangerouslySetInnerHTML={{__html:info.body}}>

                    </div>
                }
                {/*底部图表区域*/}
                <div className={'tab-bar'}>
                    <div className="back" onClick={() => navigate(-1)}><LeftOutline /></div>
                    <div className="icons">
                        <Badge content={extra ? extra.comments : 0}><MessageOutline /></Badge>
                        <Badge content={extra ? extra.popularity : 0}><LikeOutline /></Badge>
                        <span className={'stored'}><StarOutline /></span>
                        <span><MoreOutline /></span>
                    </div>
                </div>
           </div>
}

export default Detail
